<template>
  <view class="container">
    <view class="selector-container">
      <!-- 位置选择的多级结构 -->
      <template v-if="title === '位置'">
        <view class="level-selector" v-for="(level, lIdx) in selectionLevels" :key="lIdx">
          <!--   <view class="level-title">{{levelTitles[lIdx]}}</view> -->
          <scroll-view scroll-y class="level-options">
            <view v-for="(item, idx) in level.options" :key="idx" class="option-item"
              :class="{ active: level.selectedIndex === idx }" @click="selectLevelOption(lIdx, idx)">
              {{ item.name }}
            </view>
          </scroll-view>
        </view>
      </template>

      <!-- 对象选择的两级结构 -->
      <template v-else-if="title === '对象'">
        <view class="level-selector" v-for="(level, lIdx) in objectLevels" :key="lIdx">
          <scroll-view scroll-y class="level-options">
            <view v-for="(item, idx) in level.options" :key="idx" class="option-item"
              :class="{ active: level.selectedIndex === idx }" @click="selectObjectLevel(lIdx, idx)">
              {{ item.name }}
            </view>
          </scroll-view>
        </view>
      </template>
    </view>
  </view>
</template>

<script>
  import {
    ajax
  } from '../../utils/request.js';
  export default {
    data() {
      return {
        title: '',
        // For location selection
        selectionLevels: [{
            title: '区域',
            options: [],
            selectedIndex: -1,
            selectedItem: null
          },
          {
            title: '楼栋',
            options: [],
            selectedIndex: -1,
            selectedItem: null
          },
          {
            title: '楼层',
            options: [],
            selectedIndex: -1,
            selectedItem: null
          },
          {
            title: '房间',
            options: [],
            selectedIndex: -1,
            selectedItem: null
          }
        ],
        levelTitles: ['选择区域', '选择楼栋', '选择楼层', '选择房间'],

        // For repair object selection
        objectLevels: [{
            options: [],
            selectedIndex: -1,
            selectedItem: null
          },
          {
            options: [],
            selectedIndex: -1,
            selectedItem: null
          }
        ],
        currentField: ''
      };
    },
    computed: {
      activeSubOptions() {
        return this.title === '对象' ?
          (this.objectLevels[0].selectedItem?.children || []) : [];
      }
    },
    onLoad(options) {
      this.title = options.title || '选项';
      const eventChannel = this.getOpenerEventChannel();

      eventChannel.on('setField', (data) => {
        this.currentField = data.field;

        if (this.title === '位置') {
          ajax('/api/dixiu/getlocation', 'POST').then(res => {
            console.log(res.data);
            this.selectionLevels[0].options = res.data.locations;
          });
        } else if (this.title === '对象') {
          ajax('/api/dixiu/getrepairobject', 'POST').then(res => {
            console.log(res.data);
            this.objectLevels[0].options = res.data.repairObjectTree;
          });
        }
      });
    },
    methods: {
      selectCategory(index) {
        this.activeIndex = index;
      },

      selectObjectLevel(levelIndex, optionIndex) {
        const level = this.objectLevels[levelIndex];
        level.selectedIndex = optionIndex;
        level.selectedItem = level.options[optionIndex];

        if (levelIndex === 0 && level.selectedItem.children) {
          this.objectLevels[1].options = level.selectedItem.children;
          this.objectLevels[1].selectedIndex = -1;
          this.objectLevels[1].selectedItem = null;
        } else {
          const eventChannel = this.getOpenerEventChannel();
          // 对于对象选择，返回从第一级到最后一级的完整选择信息
          const selectedData = {
            name: this.objectLevels
              .filter(l => l.selectedItem)
              .map(l => l.selectedItem.name)
              .join(' '),
            id: this.objectLevels[0].selectedItem.id,
            fullPath: this.objectLevels
              .filter(l => l.selectedItem)
              .map(l => ({
                id: l.selectedItem.id,
                name: l.selectedItem.name
              }))
          };
          eventChannel.emit('acceptDataFromSelector', selectedData);
          uni.navigateBack();
        }
      },

      selectLevelOption(levelIndex, optionIndex) {
        const level = this.selectionLevels[levelIndex];
        level.selectedIndex = optionIndex;
        level.selectedItem = level.options[optionIndex];

        // Update next level options if not last level
        if (levelIndex < this.selectionLevels.length - 1) {
          const nextLevel = this.selectionLevels[levelIndex + 1];
          nextLevel.options = level.selectedItem[this.getNextLevelKey(levelIndex)] || [];
          nextLevel.selectedIndex = -1;
          nextLevel.selectedItem = null;

          // Clear deeper levels
          for (let i = levelIndex + 2; i < this.selectionLevels.length; i++) {
            this.selectionLevels[i].options = [];
            this.selectionLevels[i].selectedIndex = -1;
            this.selectionLevels[i].selectedItem = null;
          }
        } else {
          // Last level selected - return full path
          const eventChannel = this.getOpenerEventChannel();
          // 对于位置选择，返回完整路径
          const selectedData = {
            name: this.selectionLevels.map(l => l.selectedItem.name).join(' '),
            id: this.selectionLevels[0].selectedItem.id,
            fullPath: this.selectionLevels.map(l => ({
              id: l.selectedItem.id,
              name: l.selectedItem.name
            }))
          };
          eventChannel.emit('acceptDataFromSelector', selectedData);
          uni.navigateBack();
        }
      },

      getNextLevelKey(levelIndex) {
        console.log('Getting next level key for level:', levelIndex);
        const keys = ['buildings', 'floors', 'rooms'];
        const key = keys[levelIndex] || 'children';
        console.log('Using key:', key);
        return key;
      }
    }
  };
</script>

<style scoped>
  .container {
    padding: 20rpx;
    height: 100vh;
    box-sizing: border-box;
  }

  .header {
    padding: 20rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .selector-container {
    display: flex;
    height: calc(100% - 80rpx);
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  }

  .level-selector {
    flex: 1;
    padding: 20rpx;
    border-right: 1rpx solid #f0f0f0;
  }

  .level-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }

  .level-options {
    height: calc(100% - 60rpx);
  }

  .main-category {
    width: 30%;
    background-color: #f5f5f5;
    overflow-y: auto;
  }

  .sub-options {
    width: 70%;
    background-color: #fff;
    overflow-y: auto;
  }

  .option-item {
    padding: 25rpx 5rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    align-items: center;

    border-bottom: 1rpx solid #f0f0f0;
  }

  .option-item.active {
    background-color: #2BA245;
    color: white;
    font-weight: bold;
  }

  .option-item:active {
    background-color: #f5f5f5;
  }
</style>